<template>
    <n-grid :cols="24">
        <n-gi :span="24">
            <n-space>
                <n-button type="primary" size="small" ghost @click="addDlgVisible = true" :disabled="showDone">
                    添加
                </n-button>
                <n-button type="default" size="small" ghost @click="showDone = !showDone">
                    {{showDone?'显示未完成':'显示已完成'}}
                </n-button>
                <n-button type="default" size="small" @click="test1">test1</n-button>
                <n-button type="default" size="small" @click="window_center">居中</n-button>
                <n-button type="default" size="small" @click="window_close">关闭</n-button>
                <n-button type="default" size="small" @click="test2">监视器</n-button>
                <n-button type="default" size="small" @click="test3">检测通知权限</n-button>
                <n-button type="default" size="small" @click="test4">发送通知1</n-button>
                <n-button type="default" size="small" @click="test5">发送通知2</n-button>
            </n-space>
        </n-gi>
    </n-grid>
    <n-scrollbar :style="{'max-height': tableHeight+'px'}">
        <n-grid :cols="1" style="margin:2px;">
            <n-gi v-for="todo in todoData" :key="todo.t_id" style="border-bottom: 1px solid #E4F0FD;">
                <n-grid :cols="24">
                    <n-gi :span="1">
                        <n-checkbox @update:checked="handleCheckedChange(todo)" style="line-height: 45px;" v-if="todo.t_state=='0'"></n-checkbox>
                    </n-gi>
                    <n-gi :span="21">
                        <n-grid :cols="1">
                            <n-gi><n-gradient-text @click="showTodo(todo)" :type="getTitleColor(todo)">{{todo.t_title}}</n-gradient-text></n-gi>
                            <n-gi>{{todo.end_date}}</n-gi>
                        </n-grid>
                    </n-gi>
                    <n-gi :span="2">
                        <n-button type="error" size="small" style="margin-top: 8px;" @click="delTodo(todo)">删除</n-button>
                    </n-gi>
                </n-grid>
            </n-gi>
            
        </n-grid>
        <!-- <n-list hoverable >
            <n-list-item>
                <n-thing title-extra="extra" description="description" >
                    <template #title>
                        <span>xxxx</span>
                    </template>
                </n-thing>
            </n-list-item>
            <n-list-item v-for="todo in todoData" :key="todo.t_id">
                <template #prefix>
                    <n-checkbox @update:checked="handleCheckedChange(todo)"></n-checkbox>
                </template>
                <n-thing :title="todo.t_title" content-style="margin-top: 1px;">
                    {{todo.end_date+" "+todo.remind_time}}
                </n-thing>
            </n-list-item>
        </n-list> -->
    </n-scrollbar>
    
    <n-modal v-model:show="addDlgVisible"
        preset="dialog"
        title="添加"
        :mask-closable="false"
        :on-after-leave="closeEditTodoDlgEnv"
        >
        <n-form
            :model="todoForm"
            label-placement="left"
            label-width="auto"
            require-mark-placement="right-hanging"
            size="small">
            <n-form-item label="事项内容">
                <n-input v-model:value="todoForm.todo.t_title" 
                    type="textarea" :autosize="{minRows:2,maxRows:4}" maxlength="512" show-count/>
            </n-form-item>
            <n-form-item label="优先级">
                <n-select :options="levelOptions" v-model:value="todoForm.todo.priority_level"/>
            </n-form-item>
            <n-form-item label="任务日期">
                <n-date-picker  
                    style="width:100%;" 
                    v-model:formatted-value="todoForm.todo.end_date" 
                    type="date" 
                    value-format="yyyy-MM-dd"/>
            </n-form-item>
            <n-form-item label="提醒时间" v-if="todoForm.todo.end_date">
                <!-- <n-date-picker 
                    style="width:100%;" 
                    v-model:formatted-value="todoForm.todo.remind_time" 
                    type="datetime" 
                    clearable 
                    value-format="yyyy-MM-dd HH:mm:ss"/> -->
                <n-time-picker 
                    v-model:formatted-value="todoForm.todo.remind_time"
                    clearable
                    format="HH:mm"
                    />
            </n-form-item>
            <!-- <n-form-item label="重复规则" v-if="todoForm.todo.end_date">
                <n-select 
                    :options="repeatOptions" 
                    v-model:value="todoForm.todo.repeat_rule" 
                    :on-update:value="repeatChange"/>
            </n-form-item> -->
            
            
        </n-form>
        <template #action>
            <n-space>
                <n-button type="info" size="small" @click="addDlgHandle">保存</n-button>
                <n-button size="small" @click="addDlgVisible = false">取消</n-button>
            </n-space>
        </template>
    </n-modal>
    <n-modal v-model:show="customDlgVisible"
        preset="dialog"
        title="自定义重复周期">
        <n-grid :cols="2">
            <n-gi>
                <n-input-number :min="1" :max="56" v-model:value="todoForm.todo.rule_detail.interval"/>
            </n-gi>
            <n-gi>
                <n-select v-model:value="todoForm.todo.rule_detail.unit" :options="customUnits" :on-update:value="customRepeatChange"/>
            </n-gi>
            <!--<n-gi :span="2" v-if="todoForm.todo.rule_detail.unit == 'week'">
                <n-checkbox-group v-model:value="todoForm.todo.rule_detail.expand">
                    <n-space item-style="display:flex;">
                        <n-checkbox value="1" label="周一"/>
                        <n-checkbox value="2" label="周二"/>
                        <n-checkbox value="3" label="周三"/>
                        <n-checkbox value="4" label="周四"/>
                        <n-checkbox value="5" label="周五"/>
                        <n-checkbox value="6" label="周六"/>
                        <n-checkbox value="7" label="周日"/>
                    </n-space>
                </n-checkbox-group>
            </n-gi>-->
        </n-grid>
        <template #action>
            <n-space>
                <n-button type="info" size="small" @click="customDlgVisible = false">确定</n-button>
                <n-button size="small" @click="customDlgVisible = false">取消</n-button>
            </n-space>
        </template>
    </n-modal>
    <n-drawer v-model:show="showRight" :width="500" placement="right" :on-after-leave="closeRight">
        <n-drawer-content title="详情">
            <n-form
                :model="todoForm"
                label-placement="left"
                label-width="auto"
                require-mark-placement="right-hanging"
                size="small">
                <n-form-item label="事项内容">
                    <n-input v-model:value="todoForm.todo.t_title" 
                        type="textarea" :autosize="{minRows:2,maxRows:4}" maxlength="512" show-count/>
                </n-form-item>
                <n-form-item label="优先级">
                    <n-select :options="levelOptions" v-model:value="todoForm.todo.priority_level"/>
                </n-form-item>
                <n-form-item label="截止日期" >
                    <n-date-picker  style="width:100%;" v-model:formatted-value="todoForm.todo.end_date" type="date" 
                        value-format="yyyy-MM-dd"/>
                </n-form-item>
                <n-form-item label="提醒时间">
                    <n-date-picker style="width:100%;" v-model:formatted-value="todoForm.todo.remind_time" type="datetime" 
                        clearable value-format="yyyy-MM-dd HH:mm:ss"/>
                </n-form-item>
                <!-- <n-form-item label="重复规则">
                    <n-select :options="repeatOptions" v-model:value="todoForm.todo.repeat_rule" 
                        :on-update:value="repeatChange"/>
                </n-form-item> -->
                
                
            </n-form>
            <n-space justify="center">
                <n-button type="info" size="small" @click="todoSave(false)">保存修改</n-button>
            </n-space>
        </n-drawer-content>
    </n-drawer>
</template>
<script setup>
import { invoke } from '@tauri-apps/api/core';

import {ref,reactive,h, watch} from 'vue';
import { useMessage,NButton,useDialog,NSpace,NText,NGrid,NGi } from "naive-ui";
import { isPermissionGranted,sendNotification,requestPermission  } from '@tauri-apps/plugin-notification';
import { WebviewWindow } from '@tauri-apps/api/webviewWindow';
import { getCurrentWindow } from '@tauri-apps/api/window';

const message = useMessage();
const dialog = useDialog();

const addDlgVisible = ref(false);
const customDlgVisible = ref(false);
const todoData = ref([]);
const tableHeight = ref(300);
const showDone = ref(false);
const showRight = ref(false);

const todoForm = ref({
    todo:{
        t_id: '',
        t_title: '',
        end_date: null,
        remind_time: null,
        repeat_rule: 'noRepeat',
        rule_detail: {
            interval: 1,
            unit: 'day',
            expand: []
        },
        priority_level: '100'
    }
});
const customUnits = ref([
    {
        label:'天',
        value:'day'
    },{
        label:'周',
        value:'week',
    },{
        label:'月',
        value:'month'
    },{
        label:'年',
        value:'year'
    }
]);
const levelOptions = ref([
    {
        label: '重要且紧急',
        value: '400'
    },
    {
        label: '重要不紧急',
        value: '300'
    },
    {
        label: '不重要但紧急',
        value: '200'
    },
    {
        label: '不重要不紧急',
        value: '100'
    }
]);
const repeatOptions = ref([
    {
        label:'从不',
        value:'noRepeat'
    },
    {
        label:'每天',
        value:'everyDay'
    },{
        label: "工作日",
        value: "workDay"
    },{
        label: "每周",
        value: "everyWeek"
    },{
        label: "每月",
        value: "everyMonth"
    },{
        label: "每年",
        value: "everyYear"
    },{
        label: '自定义',
        value: 'custom'
    }
]);

getAllTodo();
computedTableHight();

watch(
    showDone,
    (newValue, oldValue) => {
        getAllTodo();
    }
);

function test1(){
    console.log('test1....')
    const webview = new WebviewWindow('my-label', {
    url: 'https://www.baidu.com'
    });
    webview.once('tauri://created', function () {
    // webview window successfully created
    });
    webview.once('tauri://error', function (e) {
    // an error happened creating the webview window
    });
}
function test2(){
    //返回所有的监视器
    const monitors = availableMonitors();
    console.log(monitors);
}
async function test3(){
    let permissionGranted = await isPermissionGranted();
    console.log(permissionGranted);
    if(!permissionGranted){
        const permission = await requestPermission();
        permissionGranted = permission === 'granted';
    }
    if(permissionGranted){
        sendNotification({title:'Tauri',body:'Tauri is awesome!'});
    }
}
function test4(){
    sendNotification('Tauri is awesome!');
  
}
function test5(){
    sendNotification({ title: 'TAURI', body: 'Tauri is awesome!' });
}
async function window_center(){
    await getCurrentWindow().center();
}
async function window_close(){
    await getCurrentWindow().close();
}
// const unlisten = await appWindow.onMoved(({ payload: position }) => {
//  console.log('Window moved', position);
// });

// // you need to call unlisten if your handler goes out of scope e.g. the component is unmounted
// unlisten();

function getTitleColor(todo){
    if(todo.priority_level == '400'){
        return 'danger';
    }else if(todo.priority_level == '300'){
        return 'warning';
    }else if(todo.priority_level == '200'){
        return 'info'
    }else{
        return 'success'
    }
}
function computedTableHight(){
    tableHeight.value = window.innerHeight-40;
    console.log(tableHeight.value);
}

window.addEventListener('resize',()=>{
    computedTableHight();
});
function showTodo(todo){
    console.log(todo);
    todoForm.value.todo = JSON.parse(JSON.stringify(todo));
    //todoForm.value.todo = {...todo.value};
    todoForm.value.todo.end_date = todo.end_date||null;
    todoForm.value.todo.remind_time = todo.remind_time||null;
    todoForm.value.todo.rule_detail = JSON.parse(todo.rule_detail);
    console.log(todoForm.value);

    showRight.value = true;
}
function closeRight(){
    resetTodoForm();
}
async function getAllTodo(){
    todoData.value = await invoke('get_todo_list',{tState:showDone.value?'1':'0'});
    console.log(todoData.value);
}
function repeatChange(value,option){
    console.log(value,option);
    if(value == 'custom'){
        customDlgVisible.value = true;
    }
    todoForm.value.todo.repeat_rule = value;
}
function customRepeatChange(value,option){
    if(value != 'week'){
        todoForm.value.todo.rule_detail.expand = [];
    }
    todoForm.value.todo.rule_detail.unit = value;
}
function addDlgHandle(){
    console.log(todoForm.value);
    
    if(todoSave(true)){
        addDlgVisible.value = false;
    }
}
async function todoSave(add){
    let saveObj = {
        tId: todoForm.value.todo.t_id,
        tTitle: todoForm.value.todo.t_title,
        endDate: todoForm.value.todo.end_date??'',
        remindTime: todoForm.value.todo.remind_time??'',
        repeatRule: todoForm.value.todo.repeat_rule,
        ruleDetail: JSON.stringify(todoForm.value.todo.rule_detail),
        priorityLevel: todoForm.value.todo.priority_level,
        
    };
    saveObj.firstEndDate = add ? saveObj.endDate : todoForm.value.first_end_date;
    //如果没有提醒时间，那么就没有截止日期

    let ret = await invoke('todo_save',saveObj);
    if(ret){
        message.success('保存成功!');
        getAllTodo();
    }else{
        message.error('保存失败!');
    }
    return ret;
}
function closeEditTodoDlgEnv(){
    resetTodoForm();

}
function resetTodoForm(){
    todoForm.value.todo.t_id = '';
    todoForm.value.todo.t_title = '';
    todoForm.value.todo.end_date = null;
    todoForm.value.todo.remind_time = null;
    todoForm.value.todo.repeat_rule = 'noRepeat';
    todoForm.value.todo.priority_level = '100';
}
async function handleCheckedChange(todo){
    let ret = await invoke('done_todo',{tId:todo.t_id})
    if(ret){
        getAllTodo();
    }else{

    }
}
function delTodo(todo){
    dialog.warning({
        title: '删除',
        content: '确定要删除此待办吗?',
        positiveText: "确定",
        negativeText: "取消",
        onPositiveClick: ()=>{
            delTodoHandle(todo);
        }
    })
}
async function delTodoHandle(todo){
    let ret = await invoke('del_todo',{tId:todo.t_id});
    if(ret){
        message.success('删除成功!');
        getAllTodo();
    }else{
        message.error('删除失败!');
    }
}
</script>
<style scoped>
.n-list-item{
    padding: 2px 10px !important;
}
.n-gradient-text {
  font-size: 20px;
}

</style>